#light
module FSharp.WebTools.Extensions

open System
open System.Reflection

(*-----------------------------------------------------------------------------------------------*)

type System.Reflection.MethodInfo with
  member mi.GetGenericDefinitionSafe() =
    if mi.IsGenericMethod then mi.GetGenericMethodDefinition() else mi
    
  member mi.MakeGenericMethodSafe(tya) = 
    let tyarr = Seq.to_array tya
    if (tyarr.Length <> 0 && (not mi.IsGenericMethodDefinition)) ||
       (mi.IsGenericMethodDefinition && (tyarr.Length <> mi.GetGenericArguments().Length)) then
       
      // workaround for mapping F# library function -> function from "lib_core" that use only "obj" types
      // fill the type arguments with 'obj', which may fail when the generic method has constraints
      if (mi.IsGenericMethodDefinition) then
        let tyarr = Array.create (mi.GetGenericArguments().Length) (typeof<obj>)
        mi.MakeGenericMethod(tyarr)
      else
        mi
          
    elif (tyarr.Length = 0) then mi
    else mi.MakeGenericMethod(tyarr)
    
  member mi.GetGenericArgumentsSafe() =       
    if (mi.IsGenericMethod) then mi.GetGenericArguments() else [| |]
    